package com.fly.socket.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.fly.socket.service.LoginService;

@Controller
public class LoginController
{
    @Autowired
    LoginService loginservice;
    
    @Autowired
    HttpServletRequest request;
    
    @Autowired
    HttpSession httpSession;
    
    @PostMapping("/loginvalidate")
    public String loginvalidate(@RequestParam String username, @RequestParam String pic, @RequestParam("password") String pwd)
    {
        if (username == null)
        {
            return "login";
        }
        String realpwd = loginservice.getpwdbyname(username);
        if (realpwd != null && pwd.equals(realpwd))
        {
            long uid = loginservice.getUidbyname(username);
            httpSession.setAttribute("uid", uid);
            httpSession.setAttribute("username", username);
            httpSession.setAttribute("rootURL", StringUtils.substringBetween(request.getRequestURL().toString(), "://", "/loginvalidate"));
            return "chatroom";
        }
        return "fail";
    }
    
    @GetMapping({"/", "/login"})
    public String login()
    {
        return "login";
    }
    
    @GetMapping("/logout")
    public String logout()
    {
        httpSession.removeAttribute("uid");
        httpSession.removeAttribute("username");
        return "login";
    }
}
